// 统一状态持久化管理器
// 提供跨平台的状态持久化解决方案

import { StateStorage } from 'zustand/middleware';

// 持久化配置接口
export interface PersistenceConfig {
  name: string;
  version: number;
  storage?: StateStorage;
  serialize?: (state: any) => string;
  deserialize?: (str: string) => any;
  partialize?: (state: any) => any;
  merge?: (persistedState: any, currentState: any) => any;
  migrate?: (persistedState: any, version: number) => any;
  enableCompression?: boolean;
  enableEncryption?: boolean;
  encryptionKey?: string;
  maxSize?: number;
  ttl?: number;
}

// 存储项元数据
interface StorageMetadata {
  version: number;
  timestamp: number;
  size: number;
  checksum?: string;
  ttl?: number;
}

// 存储项结构
interface StorageItem<T> {
  data: T;
  metadata: StorageMetadata;
}

// Tauri存储适配器
class TauriStorage implements StateStorage {
  private storeName: string;

  constructor(storeName: string = 'default') {
    this.storeName = storeName;
  }

  async getItem(name: string): Promise<string | null> {
    try {
      // 使用Tauri的存储API
      const { invoke } = await import('@tauri-apps/api/core');
      const result = await invoke('get_storage_item', {
        store: this.storeName,
        key: name,
      });
      return result as string | null;
    } catch (error) {
      console.error('Failed to get item from Tauri storage:', error);
      return null;
    }
  }

  async setItem(name: string, value: string): Promise<void> {
    try {
      const { invoke } = await import('@tauri-apps/api/core');
      await invoke('set_storage_item', {
        store: this.storeName,
        key: name,
        value,
      });
    } catch (error) {
      console.error('Failed to set item in Tauri storage:', error);
    }
  }

  async removeItem(name: string): Promise<void> {
    try {
      const { invoke } = await import('@tauri-apps/api/core');
      await invoke('remove_storage_item', {
        store: this.storeName,
        key: name,
      });
    } catch (error) {
      console.error('Failed to remove item from Tauri storage:', error);
    }
  }
}

// 混合存储适配器（优先使用Tauri，回退到localStorage）
class HybridStorage implements StateStorage {
  private tauriStorage: TauriStorage;
  private fallbackStorage: StateStorage;

  constructor(storeName: string = 'default') {
    this.tauriStorage = new TauriStorage(storeName);
    this.fallbackStorage = {
      getItem: (name: string) => {
        try {
          return localStorage.getItem(name);
        } catch {
          return null;
        }
      },
      setItem: (name: string, value: string) => {
        try {
          localStorage.setItem(name, value);
        } catch (error) {
          console.error('Failed to set item in localStorage:', error);
        }
      },
      removeItem: (name: string) => {
        try {
          localStorage.removeItem(name);
        } catch (error) {
          console.error('Failed to remove item from localStorage:', error);
        }
      },
    };
  }

  async getItem(name: string): Promise<string | null> {
    try {
      // 首先尝试Tauri存储
      const result = await this.tauriStorage.getItem(name);
      return result;
    } catch {
      // 回退到localStorage
      return this.fallbackStorage.getItem(name);
    }
  }

  async setItem(name: string, value: string): Promise<void> {
    try {
      // 首先尝试Tauri存储
      await this.tauriStorage.setItem(name, value);
    } catch {
      // 回退到localStorage
      this.fallbackStorage.setItem(name, value);
    }
  }

  async removeItem(name: string): Promise<void> {
    try {
      // 首先尝试Tauri存储
      await this.tauriStorage.removeItem(name);
    } catch {
      // 回退到localStorage
      this.fallbackStorage.removeItem(name);
    }
  }
}

// 持久化管理器
export class PersistenceManager {
  private static instance: PersistenceManager;
  private compressionEnabled = false;
  private encryptionEnabled = false;

  static getInstance(): PersistenceManager {
    if (!PersistenceManager.instance) {
      PersistenceManager.instance = new PersistenceManager();
    }
    return PersistenceManager.instance;
  }

  // 创建存储适配器
  createStorage(storeName: string = 'default'): StateStorage {
    return new HybridStorage(storeName);
  }

  // 创建持久化配置
  createPersistConfig<T>(config: PersistenceConfig) {
    const {
      name,
      version,
      storage = this.createStorage(),
      serialize = JSON.stringify,
      deserialize = JSON.parse,
      partialize,
      merge,
      migrate,
      enableCompression = false,
      enableEncryption = false,
      encryptionKey = '',
      maxSize,
      ttl,
    } = config;

    this.compressionEnabled = enableCompression;
    this.encryptionEnabled = enableEncryption;

    return {
      name: `codegraph-${name}`,
      version,
      storage: {
        getItem: async (key: string) => {
          try {
            const rawData = await storage.getItem(key);
            if (!rawData) return null;

            // 解密
            const decryptedData = this.decrypt(rawData, encryptionKey);
            
            // 解压
            const decompressedData = this.decompress(decryptedData);
            
            // 反序列化
            const item: StorageItem<T> = deserialize(decompressedData);
            
            // 检查TTL
            if (this.isExpired(item.metadata)) {
              await storage.removeItem(key);
              return null;
            }

            // 验证完整性
            if (item.metadata.checksum) {
              const dataStr = serialize(item.data);
              if (!this.verifyIntegrity(dataStr, item.metadata.checksum)) {
                console.warn(`Data integrity check failed for ${key}`);
                return null;
              }
            }

            return item.data;
          } catch (error) {
            console.error(`Failed to get persisted state for ${key}:`, error);
            return null;
          }
        },

        setItem: async (key: string, value: T) => {
          try {
            // 分割状态
            const dataToStore = partialize ? partialize(value) : value;
            
            // 序列化
            const serializedData = serialize(dataToStore);
            
            // 检查大小限制
            if (maxSize && serializedData.length > maxSize) {
              throw new Error(`Data size (${serializedData.length}) exceeds maximum size (${maxSize})`);
            }

            // 创建存储项
            const item: StorageItem<T> = {
              data: dataToStore,
              metadata: {
                version,
                timestamp: Date.now(),
                size: serializedData.length,
                checksum: this.calculateChecksum(serializedData),
                ttl,
              },
            };

            // 序列化完整项
            const itemStr = serialize(item);
            
            // 压缩
            const compressedData = this.compress(itemStr);
            
            // 加密
            const encryptedData = this.encrypt(compressedData, encryptionKey);
            
            // 存储
            await storage.setItem(key, encryptedData);
          } catch (error) {
            console.error(`Failed to persist state for ${key}:`, error);
          }
        },

        removeItem: async (key: string) => {
          try {
            await storage.removeItem(key);
          } catch (error) {
            console.error(`Failed to remove persisted state for ${key}:`, error);
          }
        },
      },
      partialize,
      merge: (persistedState: any, currentState: any) => {
        if (merge) {
          return merge(persistedState, currentState);
        }
        return { ...currentState, ...persistedState };
      },
      migrate: (persistedState: any, persistedVersion: number) => {
        if (migrate && persistedVersion !== version) {
          return migrate(persistedState, persistedVersion);
        }
        return persistedState;
      },
    };
  }

  // 压缩数据
  private compress(data: string): string {
    if (!this.compressionEnabled) return data;
    
    try {
      // 简单的压缩实现（实际项目中可以使用更好的压缩算法）
      return btoa(data);
    } catch {
      return data;
    }
  }

  // 解压数据
  private decompress(data: string): string {
    if (!this.compressionEnabled) return data;
    
    try {
      return atob(data);
    } catch {
      return data;
    }
  }

  // 加密数据
  private encrypt(data: string, key: string): string {
    if (!this.encryptionEnabled || !key) return data;
    
    try {
      // 简单的XOR加密（实际项目中应使用更安全的加密算法）
      let encrypted = '';
      for (let i = 0; i < data.length; i++) {
        encrypted += String.fromCharCode(
          data.charCodeAt(i) ^ key.charCodeAt(i % key.length)
        );
      }
      return btoa(encrypted);
    } catch {
      return data;
    }
  }

  // 解密数据
  private decrypt(data: string, key: string): string {
    if (!this.encryptionEnabled || !key) return data;
    
    try {
      const encrypted = atob(data);
      let decrypted = '';
      for (let i = 0; i < encrypted.length; i++) {
        decrypted += String.fromCharCode(
          encrypted.charCodeAt(i) ^ key.charCodeAt(i % key.length)
        );
      }
      return decrypted;
    } catch {
      return data;
    }
  }

  // 计算校验和
  private calculateChecksum(data: string): string {
    let hash = 0;
    for (let i = 0; i < data.length; i++) {
      const char = data.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // 转换为32位整数
    }
    return hash.toString(16);
  }

  // 验证完整性
  private verifyIntegrity(data: string, checksum: string): boolean {
    return this.calculateChecksum(data) === checksum;
  }

  // 检查是否过期
  private isExpired(metadata: StorageMetadata): boolean {
    if (!metadata.ttl) return false;
    return Date.now() - metadata.timestamp > metadata.ttl;
  }

  // 清理过期数据
  async cleanupExpiredData(storage: StateStorage): Promise<void> {
    // 这里需要实现清理逻辑
    // 由于StateStorage接口限制，我们无法枚举所有键
    // 在实际实现中，可能需要维护一个键的列表
    console.log('Cleanup expired data - implementation needed');
  }

  // 获取存储统计信息
  async getStorageStats(storage: StateStorage): Promise<{
    totalSize: number;
    itemCount: number;
    oldestItem: number;
    newestItem: number;
  }> {
    // 这里需要实现统计逻辑
    // 由于StateStorage接口限制，我们无法枚举所有键
    return {
      totalSize: 0,
      itemCount: 0,
      oldestItem: 0,
      newestItem: 0,
    };
  }
}

// 导出单例实例
export const persistenceManager = PersistenceManager.getInstance();
